package com.hkts.naturalgas.performance.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hkts.naturalgas.constant.PerformanceConstant;
import com.hkts.naturalgas.feign.FeignInterface;
import com.hkts.naturalgas.index.entity.ParamVo;
import com.hkts.naturalgas.organizational.entity.HontPost;
import com.hkts.naturalgas.organizational.entity.HontUser;
import com.hkts.naturalgas.organizational.service.IHontPostService;
import com.hkts.naturalgas.organizational.service.IHontUserService;
import com.hkts.naturalgas.performance.entity.HkAssessmentInfo;
import com.hkts.naturalgas.performance.entity.HkAssessmentScore;
import com.hkts.naturalgas.performance.mapper.HkAssessmentScoreMapper;
import com.hkts.naturalgas.performance.performanceTo.HontUserTo;
import com.hkts.naturalgas.performance.performanceTo.PerformanceTo;
import com.hkts.naturalgas.performance.performanceTo.SubmitPerformanceDTo;
import com.hkts.naturalgas.performance.performanceVo.HistoryCommentAndScoreVo;
import com.hkts.naturalgas.performance.performanceVo.PerformanceInfoNameAndUserNickVo;
import com.hkts.naturalgas.performance.performanceVo.PerformanceScoreListVo;
import com.hkts.naturalgas.performance.service.IHkAssessmentInfoService;
import com.hkts.naturalgas.performance.service.IHkAssessmentScoreService;
import com.hkts.naturalgas.utils.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author yck
 * @since 2020-12-23
 */
@RestController
@RequestMapping("/performance/hkAssessmentScore")
public class HkAssessmentScoreController {
    private final Logger logger = LoggerFactory.getLogger(HkAssessmentScoreController.class);

    @Autowired
    public IHkAssessmentScoreService iHkAssessmentScoreService;
    @Autowired
    public IHkAssessmentInfoService iHkAssessmentInfoService;

    @Autowired
    public IHontUserService iHontUserService;

    @Autowired
    public IHontPostService iHontPostService;

    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    private HkAssessmentScoreMapper hkAssessmentScoreMapper;
    /**
     * 分页查询数据
     *
     * @param page              分页信息
     * @param hkAssessmentScore 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getHkAssessmentScorePageList")
    public Result<Object> getHkAssessmentScorePageList(Page<HkAssessmentScore> page, HkAssessmentScore hkAssessmentScore) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHkAssessmentScoreService.selectPage(page, hkAssessmentScore)));
    }

    /**
     * 保存和修改公用的
     *
     * @param hkAssessmentScore 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hkAssessmentScoreSave")
    public Result<Object> hkAssessmentScoreSave(HkAssessmentScore hkAssessmentScore) {
        iHkAssessmentScoreService.saveOrUpdate(hkAssessmentScore);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hkAssessmentScoreGetById")
    public Result<Object> hkAssessmentScoreGetById(String id) {
        HkAssessmentScore byId = iHkAssessmentScoreService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hkAssessmentScoreDelete")
    public Result<Object> hontUserDelete(String id) {
        iHkAssessmentScoreService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hkAssessmentScoreBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iHkAssessmentScoreService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    /*
     * 将审核内容分数chi'jiu  addNewAssessmentScore
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addNewAssessmentScore")
    public Result<Object> addNewAssessmentScore(@RequestParam String list, String hontUserId, String createTime,String submissionKey) throws Exception {
        PerformanceTo item = new PerformanceTo();
        item.setCreateTime(createTime);
        item.setList(list);
        item.setHountUserId(hontUserId);
        item.setSubmissionKey(submissionKey);
        iHkAssessmentScoreService.saveScoreAndForm(item);
        return ResultUtil.success("添加成功");
    }

    /*首次提交考核
     * 将审核内容分数chi'jiu  addNewAssessmentScore v1.5
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addNewAssessmentScoreTo")
    public Result<Object> addNewAssessmentScoreTo(@RequestBody SubmitPerformanceDTo submitPerformanceDTo) throws Exception {
        iHkAssessmentScoreService.saveScoreAndFormTo(submitPerformanceDTo);
        return ResultUtil.success("添加成功");
    }

    /*
     * 根据流程id 查找ren
     * */
    @ResponseBody
    @PostMapping("/getHkAssessmentScoreByProIds")
    public List<Map> getHkAssessmentScoreByProIds(@RequestBody List<String> ids) {
        List<Map> listResult = new ArrayList<>();
        PerformanceTo item = new PerformanceTo();

        List<HkAssessmentScore> list = iHkAssessmentScoreService.getHkAssessmentScoreByProIds(ids);
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("hontUserId", list.get(i).getHontUserId());
            map.put("processInstanceId", list.get(i).getProcessInstanceId());
            listResult.add(map);
        }
        return listResult;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/selectScore")
    public Result<Object> selectScore(){
        Map<String, Object> stringMapMap = iHkAssessmentScoreService.selectScoreByHontUserOnDepartementPositive();
        return ResultUtil.data(stringMapMap);
    }
    @RequestMapping(method = RequestMethod.GET, value = "/selectHistory")
    public Result<Object> selectHistory(CustomPage page) throws ParseException {
        CustomPage customPage = iHkAssessmentScoreService.selectHistoryByHontUser(page);
        return ResultUtil.data(customPage);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/selectHistoryByProcessId")
    public Result<Object> selectHistoryByProcessId(String processId) {
        Map<String, Object> maps = iHkAssessmentScoreService.selectHistoryByProcessId(processId);
        return ResultUtil.data(maps);
    }
    /*
     * 待办数量
     * */
    @GetMapping(value = "/get-performance-applying-tasks-num")
    public Result  getPerformanceApplyingTasksNum() {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        List<String> dealtWith = iHkAssessmentInfoService.getDealtWith(hontUserTo.getId());
        Map mm=new HashMap();
        mm.put("num",dealtWith.size());
        return ResultUtil.data(mm);
    }


    /*
     * 待办列表
     * */
    @ResponseBody
    @GetMapping("/getHkAssessmentInfoAndUserNickNameByProIds")
    public Result<LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>>> getHkAssessmentInfoAndUserNickNameByProIds() {
        Result<LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>>> list = iHkAssessmentScoreService.getHkAssessmentInfoAndUserNickNameByProIds();
        return list;
    }

    /*
     * 根据流程id查询得分情况
     * */
    @ResponseBody
    @GetMapping("/getHkAssessmentScoreByProId")
    public Result getHkAssessmentScoreByProId(String proessId) {
        Map<String, Object> resultMap = new HashMap<>();
        Float totalScore = (float) 0;
        List<PerformanceScoreListVo> list = iHkAssessmentScoreService.getHkAssessmentScoreByProId(proessId);
        for (int i = 0; i < list.size(); i++) {
            totalScore = totalScore + list.get(i).getScore();
        }
        //根据流程id获取数据
        HkAssessmentScore score=new HkAssessmentScore();
        score.setProcessInstanceId(proessId);
        score.setIsCurrentAssessment("1");
        List<HkAssessmentScore> hkAssessmentScores = iHkAssessmentScoreService.selectList(score);
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MM.dd HH:mm");
        resultMap.put("totalScore", totalScore);
        resultMap.put("list", list);
        resultMap.put("time", dtf2.format(hkAssessmentScores.get(0).getCreateTime()));
        HontUser user=new HontUser();
        user.setId(hkAssessmentScores.get(0).getHontUserId());
        QueryWrapper<HontUser> query = Wrappers.query();
        query.eq(HontUser.ID,hkAssessmentScores.get(0).getHontUserId());
        List<HontUser> list1 = iHontUserService.list(query);
        System.out.println("nickName"+list1.get(0).getNickName());
        resultMap.put("nickName",list1.get(0).getNickName());
        resultMap.put("hont_user_id",hkAssessmentScores.get(0).getHontUserId());
        if(StringUtils.isNotBlank(list1.get(0).getPostId())){
            HontPost post=new HontPost();
            post.setId(list1.get(0).getPostId());
            List<HontPost> hontPosts = iHontPostService.selectList(post);
            if(hontPosts.size()>0){
                System.out.println("postTitle:"+hontPosts.get(0).getTitle());
                resultMap.put("postTitle",hontPosts.get(0).getTitle());
            }
        }
        HkAssessmentInfo info=new HkAssessmentInfo();
        info.setProcessInstanceId(proessId);
        List<HkAssessmentInfo> hkAssessmentInfos = iHkAssessmentInfoService.selectList(info);
        DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        resultMap.put("title",dtf3.format(hkAssessmentInfos.get(0).getCreateTime())+"绩效考核");
        return ResultUtil.data(resultMap);
    }

    /*-------
     * 分数审核成功XXXXXX
     * */
    @ResponseBody
    @PostMapping("/approvalWithoutScore")
    public Result approvalWithoutScore(String processInstanceId, String taskId) throws Exception {
        Map<String, Object> map = iHkAssessmentScoreService.approvalWithoutScore(processInstanceId, taskId);
        return ResultUtil.data(map);
    }

    /*
    *
     * 分数修改并审核
     * */
  @ResponseBody
    @PostMapping("/approvalWithScore")
    public Result approvalWithoutScore(@RequestParam String list,String processInstanceId, String taskId) throws Exception {
        Map<String, Object> map = iHkAssessmentScoreService.approvalWithScore(list,processInstanceId, taskId);
        return ResultUtil.data(map);
    }

    /*
     *
     * 分数修改并审核(v1.5)
     * */
    @ResponseBody
    @PostMapping("/approvalWithScoreVf")
    public Result approvalWithoutScore(@RequestBody SubmitPerformanceDTo submitPerformanceDTo) throws Exception {
        Map<String, Object> map = iHkAssessmentScoreService.approvalWithScoreVf(submitPerformanceDTo);
        return ResultUtil.data(map);
    }
  /*
  * 流程审核完成后进行数据修改
  * */
  @ResponseBody
  @PostMapping("/updateStateByProcessInstanceId")
  public Result updateStateByProcessInstanceId(String processInstanceId) throws Exception {
      System.out.println("远程调用成功："+processInstanceId);
      HkAssessmentScore score=new HkAssessmentScore();
      score.setProcessInstanceId(processInstanceId);
      score.setScoreState(PerformanceConstant.APPROVL_COMPLETED);
      iHkAssessmentScoreService.updateStateByProcessInstanceId(score);


      return ResultUtil.success("修改成功");
  }

  /*
  * 历史记录
  * */
    @ResponseBody
    @GetMapping("/getHistoryAndScore")
    public Result getHistoryCommentAndScore(String processInstanceId,String indexId){
     List<HistoryCommentAndScoreVo> list=   iHkAssessmentScoreService.getHistoryCommentAndScore(processInstanceId,indexId);
        return ResultUtil.data(list);
    }

    /*
    * 获取重复防止重复提交的key
    * */
    @ResponseBody
    @GetMapping("/getSubmissionKey")
    public Result getSubmissionKey(){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        String s = IDUtils.genImageName();
        redisTemplate.opsForValue().set(PerformanceConstant.SUBMISSION_KEY+ s,hontUserTo.getId(),48, TimeUnit.HOURS);
        return ResultUtil.data(s);
    }

    /*
     * 个人历史考核记录
     * */
    @ResponseBody
    @GetMapping("/getPersonHistoryPerformanceByDate")
    public Result getPersonHistoryPerformanceByDate(CustomPage page,ParamVo paramVo){
        Page<HkAssessmentScore> personPerformanceByDate = iHkAssessmentScoreService.getPersonPerformanceByDate(page, paramVo);
        return ResultUtil.data(personPerformanceByDate);
    }
    /*
     * 个人历史考核记录总扣分、总加分
     * */
    @ResponseBody
    @GetMapping("/getHistoryScorePerformanceByDate")
    public Result getHistoryScorePerformanceByDate(ParamVo paramVo){
        Map<String, Object> personPerformanceCountScoreByDate = iHkAssessmentScoreService.getPersonPerformanceCountScoreByDate(paramVo);
        return ResultUtil.data(personPerformanceCountScoreByDate);
    }

    /*
     * 个人历史及部门考核记录次数柱形图
     * */
    @ResponseBody
    @GetMapping("/getHistoryNumPerformanceByDate")
    public Result getHistoryNumPerformanceByDate(ParamVo paramVo){
        Map<String, Object> historyNumPerformanceByDate = iHkAssessmentScoreService.getHistoryNumPerformanceByDate(paramVo);
        return ResultUtil.data(historyNumPerformanceByDate);
    }
}
